const api = require('../../../utils/api');
const util = require('../../../utils/util');
const auth = require('../../../utils/auth');

Page({
  data: {
    myNews: [],
    searchText: '',
    isLoading: false,
  },

  onLoad() {
    // 页面加载时执行
  },

  onShow() {
    // 页面显示时检查登录状态并加载我的新闻
    if (auth.isLoggedIn()) {
      this.fetchMyNews();
    } else {
      wx.showModal({
        title: '提示',
        content: '您需要登录后才能查看我的新闻',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/user/login'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
    }
  },

  fetchMyNews() {
    this.setData({ isLoading: true });
    api.getMyNews().then(res => {
      const formattedNews = res.data.map(item => ({
        ...item,
        date: util.formatDateToYYYYMMDD(item.date)
      }));
      this.setData({
        myNews: formattedNews,
        isLoading: false
      });
    }).catch(err => {
      console.error('获取我的新闻失败:', err);
      wx.showToast({
        title: '获取新闻失败',
        icon: 'none',
        duration: 2000
      });
      this.setData({ isLoading: false });
    });
  },

  navigateToAddNews() {
    wx.navigateTo({
      url: '/pages/news/edit/edit'
    });
  },

  editNews(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/news/edit/edit?id=${id}`
    });
  },

  deleteNews(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除这篇新闻吗？',
      success: (res) => {
        if (res.confirm) {
          api.deleteNews(id).then(() => {
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1500
            });
            this.fetchMyNews(); // 重新加载列表
          }).catch(err => {
            console.error('删除新闻失败:', err);
            wx.showToast({
              title: '删除失败',
              icon: 'none',
              duration: 2000
            });
          });
        }
      }
    });
  },

  onSearchInput(e) {
    this.setData({
      searchText: e.detail.value
    });
  },

  searchMyNews() {
    const searchText = this.data.searchText.toLowerCase();
    
    if (!searchText) {
      // 如果搜索文本为空，重新加载所有新闻
      this.fetchMyNews();
      return;
    }

    // 如果搜索文本不为空，执行前端过滤
    const filteredNews = this.data.myNews.filter(item => 
      item.title.toLowerCase().includes(searchText) ||
      item.content.toLowerCase().includes(searchText) ||
      item.type.toLowerCase().includes(searchText)
    );
    this.setData({
      myNews: filteredNews
    });
    
    if (filteredNews.length === 0) {
      wx.showToast({
        title: '未找到相关新闻',
        icon: 'none',
        duration: 1500
      });
    }
  },
}); 